package com.bis.ymyy.controller;


import com.bis.ymyy.common.utils.*;
import com.bis.ymyy.common.exception.BusinessException;
import com.bis.ymyy.common.exception.EnumCode;
import com.bis.ymyy.entity.Doctor;
import com.bis.ymyy.entity.User;
import com.bis.ymyy.service.DoctorService;
import com.bis.ymyy.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "/用户相关接口")
public class UserController {

    @Autowired(required = false)
    private UserService userService;
    @Autowired(required = false)
    private DoctorService doctorService;

    @ApiOperation("/获取所有用户信息")
    @RequestMapping(path = "/getAllUser", method = RequestMethod.GET)
    public List<User> getAllUser(HttpServletRequest req) {
        log.info("开始查询所有用户。。。");
        List<User> userList = userService.getAllUser();
        return userList;
    }

    @ApiOperation("/分页查询用户")
    @PostMapping("/queryPageUser")
    public Result<Object> queryPageUser(@RequestBody(required = false) QueryPage page) {
        Result<Object> result = new Result<>();
        if (page != null) {
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            List<User> models = userService.getAllUser();
            PageInfo<User> pageInfo = new PageInfo<>(models);
            result.setCode(200);
            result.setSuccess(true);
            result.setMsg("success");
            result.setData(pageInfo);
        } else {
            result.setData(userService.getAllUser());
            result.setMsg("success");
            result.setSuccess(true);
        }
        return result;
    }

    @ApiOperation("/根据id查询用户")
    @GetMapping("/findUserById")
    public User findUserById(@RequestParam(name = "userId", required = true) int userId) {

        User user = userService.findUserById(userId);
        if (user == null) {
            throw new BusinessException(EnumCode.E_100116);
        }
        return user;
    }

    @ApiOperation("/根据用户名查找用户")
    @GetMapping("/findUserByName")

    public Result<User> findUserByName(@RequestParam(value = "userName") String userName) {
        Result<User> result = new Result<>();
        if (userName == null || userName.equals("")) {
            result.setCode(400);
            result.setSuccess(false);
            result.setMsg("传入用户名参数为空");
        } else {
            User user = new User();
            if (userService.findUserByUserName(userName) == null) {
                Doctor doctor = doctorService.findByUserName(userName);
                user.setUserId(doctor.getId());
                BeanUtils.copyProperties(doctor, user);
            } else user = userService.findUserByUserName(userName);
            result.setData(user);
            result.setMsg("查找成功");
            result.setCode(200);
            result.setSuccess(true);
        }
        return result;
    }

    @CrossOrigin
    @ApiOperation(value = "/用户登录", httpMethod = "POST", notes = "用户登录")
    @PostMapping("/login")
    public Result<HashMap> login(@RequestBody LoginInfo loginInfo) {
        Result<HashMap> result = new Result<>();
        result.setSuccess(false);
        result.setData(null);
        try {
            User user = userService.userLogin(loginInfo.getUserName(), loginInfo.getPassword());
            String token = TokenUtil.sign(user);
            HashMap<String, Object> hs = new HashMap<>();
            hs.put("token", token);
            hs.put("user", user);
            result.setSuccess(true);
            result.setMsg("登录成功");
            result.setCode(200);
            result.setData(hs);
        } catch (BusinessException e) {
            result.setMsg(e.getMsg());
        }
        return result;
    }

    @ApiOperation("/退出登录")
    @RequestMapping(path = "/logout", method = RequestMethod.GET)
    public Result logout(HttpServletRequest req) {
        Result result = new Result();
        /*HttpSession session = req.getSession();
        if (session.getAttribute("loginUser") == null){
            throw new BusinessException(EnumCode.E_100117);
        } else {
            session.removeAttribute("loginUser");*/
        result.setSuccess(true);
        result.setMsg("登出成功");
        result.setCode(200);
        return result;
//        }
    }

    @ApiOperation("/注册用户")
    @PostMapping("/register")
    public Result register(@RequestBody LoginInfo info) {
        Result result = new Result();
        if (info.getUserName() == "admin") {
            result.setMsg("不可注册为admin，注册失败");
            result.setCode(400);
            result.setSuccess(false);
        }
        if ((userService.addUser(info.getUserName(), info.getPassword()) == 1)
                && doctorService.findByUserName(info.getUserName()) != null) {
            result.setSuccess(true);
            result.setCode(200);
            result.setMsg("注册成功");
        } else {
            result.setMsg("用户名已存在，注册失败");
            result.setCode(400);
            result.setSuccess(false);
        }
        return result;
    }

    @PostMapping("/addBaseUser")
    public Result addBaseUser(@RequestBody AddUserInfo userInfo) {
        Result result = new Result();
        if (userInfo.getUserName() == "admin") {
            result.setMsg("不可添加为admin！");
            result.setCode(400);
            result.setSuccess(false);
        }
        User user = userService.findUserByUserName(userInfo.getUserName());
        if (user != null) {
            result.setCode(400);
            result.setSuccess(false);
            result.setMsg("用户名已存在，添加失败");
        } else if (userService.addBaseUser(userInfo)) {
            result.setMsg("添加成功");
            result.setCode(200);
            result.setSuccess(true);
            result.setData(userService.findUserByUserName(userInfo.getUserName()));
        }

        return result;
    }

    @ApiOperation("/删除用户")
    @PostMapping("/deleteUserById")
    public Result deleteUserById(@RequestBody Map params) {
        Result result = new Result();
        result.setCode(200);
        result.setMsg("删除成功");
        result.setSuccess(true);
        String[] idsArr = params.get("ids").toString().split(",");
        for (String s : idsArr) {
            userService.deleteUserById(Integer.parseInt(s));
        }
        return result;
    }

    @ApiOperation("/更新用户信息")
    @PostMapping(value = "/updateUser", produces = "application/json;charset=UTF-8")
    public Result updateUser(@RequestBody User user) {
        Result result = new Result();
        if (userService.updateUser(user) == 0) {
            result.setMsg("未修改任何数据");
            result.setSuccess(false);
            result.setCode(400);
        } else {
            result.setSuccess(true);
            result.setMsg("更新成功");
            result.setCode(200);
        }
        return result;
    }

    @ApiOperation("/获取当前登录用户基本信息")
    @GetMapping("/getInfo")
    public Result<Map> getInfo(HttpServletRequest req) {
        String token = req.getHeader("token");
        Result<Map> result = new Result<>();
        if (token == null) {
            result.setCode(402);
            result.setSuccess(false);
            result.setMsg("token为空");
        } else {
            String userName = TokenUtil.getUserNameFromToken(token);
            User user = new User();
            Doctor doctor = doctorService.findByUserName(userName);
            if (doctor != null){
                user.setUserId(doctor.getId());
                BeanUtils.copyProperties(doctor, user);
            }
            if (userService.findUserByUserName(userName) == null && doctor == null) {
                result.setMsg("用户不存在");
                result.setCode(100116);
                result.setSuccess(false);
            } else {
                if (doctor == null)
                    user = userService.findUserByUserName(userName);
                String permissions[] = new String[1];
                permissions[0] = user.getPermissions();
                Map map = new HashMap();
                map.put("permissions", permissions);
                map.put("userName", user.getUserName());
                map.put("avatar", user.getAvatar());
                result.setSuccess(true);
                result.setMsg("获取当前用户信息成功");
                result.setData(map);
                result.setCode(200);
            }
        }
        return result;

    }

}
